package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.entity.Like;
import com.itheima.wisdomnext.mapper.LikeMapper;
import com.itheima.wisdomnext.service.LikeService;
import com.itheima.wisdomnext.util.LikeS_Util;
import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private LikeMapper likeMapper;

    @Override
    public boolean addLike(Like like) {
        boolean result = likeMapper.insertLike(like) > 0;  // 插入点赞记录
        LikeS_Util.isTrue(!result, ErrorCode.FAILED, "点赞失败");

        if ("POST".equals(like.getTargetType())) {
            boolean success = likeMapper.incrementPostLikes(like.getTargetId()) > 0;
            LikeS_Util.isTrue(!success, ErrorCode.FAILED, "增加帖子点赞数失败");
            return true;
        } else if ("COMMENT".equals(like.getTargetType())) {
            boolean success = likeMapper.incrementCommentLikes(like.getTargetId()) > 0;
            LikeS_Util.isTrue(!success, ErrorCode.FAILED, "增加评论点赞数失败");
            return true;
        }

        return false; // 如果 targetType 不是 POST 或 COMMENT
    }

    @Override
    public boolean removeLike(Like like) {
        boolean result = likeMapper.deleteLike(like) > 0;  // 删除点赞记录
        LikeS_Util.isTrue(!result, ErrorCode.FAILED, "取消点赞失败");

        if ("POST".equals(like.getTargetType())) {
            boolean success = likeMapper.decrementPostLikes(like.getTargetId()) > 0;
            LikeS_Util.isTrue(!success, ErrorCode.FAILED, "减少帖子点赞数失败");
            return true;
        } else if ("COMMENT".equals(like.getTargetType())) {
            boolean success = likeMapper.decrementCommentLikes(like.getTargetId()) > 0;
            LikeS_Util.isTrue(!success, ErrorCode.FAILED, "减少评论点赞数失败");
            return true;
        }

        return false; // 如果 targetType 不是 POST 或 COMMENT
    }

    @Override
    public boolean checkIfLiked(Like like) {
        return likeMapper.selectLike(like) != null;
    }
}